/**
 * Created by whj on 2016/6/20.
 */
import React, {Component} from 'react'
import BaseComponent from 'basecomponent'
import Modal from 'rmodal'
import api from 'apis'
import Dropzone from 'react-dropzone';
import './style.scss'
import Button from 'button'
import appConfig from 'config'
import auth from 'auth'


export default class UploadMusicModal extends BaseComponent {
  constructor(props){
    super(...arguments);
    this.state={
      isShow:false,
      isUploading: false,
      isSuccess: false,
      isPicSuccess: false,
      musicName: null,
      musicDuration: 0,
      fileName: null,
      musicData:{
        Name:'',
        Image: null,
        Url: null,
        TrackNumber:0,
        TotolTrackCount:0,
        Duration:0,
        Collect:0,
        IsInCollect:false,
        Comment:0,
        PlayTimes:0,
        Price:0,
      },
    }
  }

  componentWillMount  (){
    const openAnimation = ()=>this.setState({isShow:true});
    setTimeout(openAnimation,0);
  }

  componentDidMount(){

  }

  handleMusicFileSelect(files) {
    const{musicData,musicName,musicDuration} = this.state
    let file = files[0];
    if (file) {
      this.setState({isUploading:true})
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = api.file.uploadFile(file, this.progressCallback.bind(this));
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          musicData.Name = musicName
          musicData.Url = res.Data
          musicData.Duration = musicDuration
          this.setState({fileName:file.name, isSuccess:true},this.handleAddMusicView(musicData))
        })
        .catch((err)=>{
          alert(err.msg)
          this.setState({isUploading:false,
            isSuccess:false})
        })
    }
  }
  progressCallback (ProgressEvent) {
    this.setState({progressPercent : ProgressEvent.percent.toFixed(0)})
  }

  handleAddMusicView(data){
    this.addMusicRP && this.addMusicRP.request.abort();
    this.addMusicRP = api.music.addMusic(data);
    this.registerRequest(this.addMusicRP.request);
    this.addMusicRP.promise
      .then((res)=>{
        this.setState({isUploading:false,musicData:res.Data})
      })
      .catch((err)=>{
        alert(err.msg)
        this.setState({isUploading:false,
          isSuccess:false})
      })
  }
  handlePicFileSelect(files) {
    const{musicData} = this.state
    let file = files[0];
    if (file) {
      this.setState({isUploading:true})
      this.uploadLogoRP && this.uploadLogoRP.request.abort();
      this.uploadLogoRP = api.file.uploadFile(file, this.progressCallback.bind(this));
      this.registerRequest(this.uploadLogoRP.request);
      this.uploadLogoRP.promise
        .then((res) => {
          musicData.Image = res.Data
          console.log('res', res.Data)
          this.setState({isPicSuccess: true, pic: res.Data},this.handleAddMusicView(musicData))
        })
        .catch((err)=>{
          alert(err.msg)
          this.setState({isUploading:false,
            isPicSuccess:false})
        })
    }
  }
  onReject(arg){
    alert('最大支持30MB音频类型文件')
  }

  handleClose() {
    this.setState({
      isShow: false
    });
    this.uploadLogoRP && this.uploadLogoRP.request.abort();
    this.addMusicRP && this.addMusicRP.request.abort();
    setTimeout(this.props.hideModal,300);
  }

  render(){
    const{handleSave} = this.props
    const {isShow,isUploading,musicData,fileName,isSuccess, progressPercent, isPicSuccess, pic} = this.state;
    return(
      <Modal width="540" height="480" show={isShow}>
        <Modal.Header text="上传音频" align="center" onClose={()=>{this.handleClose()}}>

        </Modal.Header>
        <Modal.Content  loadingText="正在上传" isLoadingProgress={isUploading} progress={progressPercent}>
          <input className={'name-input'} type={'text'}
                 placeholder={'名称'}
                 onChange={(e)=>{
                   this.setState({musicName: e.target.value})
                 }}
          />
          <input className={'duration-input'} type={'text'}
                 placeholder={'时长'}
                 onChange={(e)=>{
                   this.setState({musicDuration: e.target.value})
                 }}
          />
          <Dropzone className={'music-drop-zone'}
                    onDrop={this.handleMusicFileSelect.bind(this)}
                    accept={'audio/*'}
                    maxSize={31457280}
                    onDropRejected={this.onReject}
                    disabled={isSuccess && fileName}
                    multiple={false}>
            <div className={'music-default-div'}>
              {isSuccess && fileName?<span>{fileName}</span>:<Button onClick={()=>{}}>选择文件</Button>}
            </div>
          </Dropzone>
          <Dropzone className={'pic-drop-zone'}
                    onDrop={this.handlePicFileSelect.bind(this)}
                    accept={'image/*'}
                    multiple={false}>
            <div className={'music-default-div'}>
              {isPicSuccess?<img className={'music-pic'} src={`${appConfig.apiHost}/File/?pid=${pic}&key=${auth.getFileToken()}`}/> : <Button onClick={()=>{}}>选择图片</Button>}
            </div>
          </Dropzone>
          {(isSuccess || isPicSuccess) && <Button className={'save-btn'} onClick={
            ()=> {
              handleSave && handleSave(musicData)
              this.handleClose()
            }
          }>保存</Button>}
        </Modal.Content>
      </Modal>
    )
  }
}




